<template>
  <div class="agent">

    <div class="df jc-sb title-btn">
      <div>
        <el-input v-model="search_inp" @keydown.enter="search_click" placeholder="输入任意字段进行模糊查询" class="input-with-select">
          <template #append>
            <el-button @click="search_click" :icon="Search" />
          </template>
        </el-input>
      </div>
      <div><el-button type="primary" @click="create_km">添加卡密</el-button></div>
    </div>
    <el-table :data="tableData" stripe border style="width: 100%;height: 650px;margin-top: 15px;" @click="table_click">
      <el-table-column prop="IndexID" label="索引" width="150" />
      <el-table-column prop="AgentUserName" label="卡密所有者" width="150">
        <template #default="scope">
          <div @dblclick="db_click(scope.row)" v-if="scope.row.AgentUserName && !scope.row.status">{{ scope.row.AgentUserName }}</div>
          <div style="color: #ccc;" v-show="!scope.row.status" v-else @dblclick="db_click(scope.row)">双击进行编辑</div>
          <el-select v-if="scope.row.status" v-model="daili_model" filterable placeholder="请选择代理" @blur="daili_blur(scope.row)">
            <el-option v-for="item in daili_list" :key="item.AgentUserName" :label="item.AgentUserName" :value="item.AgentUserName" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="CamiBalance" label="卡密余额" width="100" />
      <el-table-column prop="CamiCreateTime" label="卡密创建时间" width="180" />
      <el-table-column prop="CamiID" label="卡密号" width="300" />
      <el-table-column prop="CamiUseTime" label="卡密使用时间" width="180" />
      <el-table-column prop="Distributor" label="卡密被分配者" />
      <el-table-column prop="OwnerUserName" label="卡密使用者" />

      <el-table-column prop="" label="操作" width="300">
        <template #default="scope">
          <!-- <el-button @click="allot(scope.row)">分配</el-button> -->
          <!-- <el-button link type="primary" @click="edit_row(scope.row)">修改</el-button> -->
          <el-popconfirm title="确定要收回吗?" confirm-button-text="确定" cancel-button-text="取消" @confirm="recycle(scope.row)">
            <template #reference>
              <el-button link type="warning">收回</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <Pagination style="margin-top: 10px;" :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></Pagination>

    <!-- 生成卡密弹框 -->
    <el-dialog draggable v-model="dialogVisible" title="生成" width="40%">
      <el-form style="padding-right: 20px;" ref="ruleFormRef" :model="km_form" :rules="km_rules" label-width="120px" class="demo-ruleForm" status-icon>
        <el-form-item label="卡密ID" prop="CamiID">
          <div class="df w100">
            <el-input style="width: 100%;margin-right: 5px;" placeholder="点击右侧获取" disabled v-model="km_form.CamiID" />
            <el-button type="primary" @click="get_cm">获取</el-button>
          </div>
        </el-form-item>
        <el-form-item label="卡密余额" prop="CamiBalance">
          <el-input v-model="km_form.CamiBalance" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="kami_enter">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改卡密弹框 -->
    <el-dialog draggable v-model="edit_dialogVisible" title="修改" width="40%">
      <el-form style="padding-right: 20px;" ref="ruleFormRef" :model="edit_from"  label-width="120px" class="demo-ruleForm" status-icon>
        <el-form-item label="卡密所有者" prop="AgentUserName">
          <!-- <el-input v-model="edit_from.AgentUserName" /> -->
          <el-select v-model="edit_from.AgentUserName" filterable placeholder="请选择代理" >
            <el-option v-for="item in daili_list" :key="item.AgentUserName" :label="item.AgentUserName" :value="item.AgentUserName" />
          </el-select>
        </el-form-item> 
        <el-form-item label="卡密余额" prop="CamiBalance"> 
          <el-input v-model="edit_from.CamiBalance" />  
        </el-form-item>
        <el-form-item label="卡密号" prop="CamiID">
          <el-input v-model="edit_from.CamiID" disabled /> 
        </el-form-item> 
        <el-form-item label="卡密被分配者" prop="Distributor">
          <el-input v-model="edit_from.Distributor" />
        </el-form-item> 
        <el-form-item label="卡密使用者" prop="OwnerUserName">
          <el-input v-model="edit_from.OwnerUserName" />
        </el-form-item> 
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="edit_dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="edit_enter">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    
  </div>
</template>   
  
  <script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import http from '../../http/index'
import Pagination from '../components/Pagination.vue'
import { useCounterStore } from '../../current/index'
import { storeToRefs } from 'pinia'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
const store = useCounterStore()
const { edit_table, formart_sql, delete_sql } = store //方法
const { userInfo } = storeToRefs(store) //  数据

onMounted(async () => {
  let total_arr = await get_list('SELECT COUNT(*) FROM cami', 'userglobal')
  total.value = Number(total_arr[0]['COUNT(*)'])

  await get_list('SELECT * FROM cami ORDER BY cami.IndexID LIMIT 15 OFFSET 0', 'userglobal')

  console.log(tableData.value)
})

const page = ref(1) //页码数
const pageSize = ref(15) //每页条数
const total = ref(10)

const handleSizeChange = async (val: number) => {
  console.log(`${val} items per page`)
  pageSize.value = val
  // page.value = 1
  // 每页显示的条数
  if ((page.value - 1) * pageSize.value - 1 <= 0) {
    await get_list(
      `SELECT * FROM cami ORDER BY cami.IndexID LIMIT ${pageSize.value} OFFSET 0`,
      'userglobal'
    )
  } else {
    await get_list(
      `SELECT * FROM cami ORDER BY cami.IndexID LIMIT ${pageSize.value} OFFSET ${
        (page.value - 1) * pageSize.value
      }`,
      'userglobal'
    )
  }
}
const handleCurrentChange = async (val: number) => {
  console.log(`current page: ${val}`)
  page.value = val
  // 当前页码数
  if ((val - 1) * pageSize.value - 1 <= 0) {
    await get_list(
      `SELECT * FROM cami ORDER BY cami.IndexID LIMIT ${pageSize.value} OFFSET 0`,
      'userglobal'
    )
  } else {
    await get_list(
      `SELECT * FROM cami ORDER BY cami.IndexID LIMIT ${pageSize.value} OFFSET ${
        (page.value - 1) * pageSize.value
      }`,
      'userglobal'
    )
  }
}

// 生成卡密模块
const km_form = ref({
  CamiID: '',
  CamiBalance: ''
})
const km_rules = ref({
  CamiID: [{ required: true, message: '请获取卡密ID', trigger: 'blur' }],
  CamiBalance: [{ required: true, message: '请输入卡密余额', trigger: 'blur' }]
})
const dialogVisible = ref(false)
const create_km = () => {
  dialogVisible.value = true
}
const kami_enter = async () => {
  if (km_form.value.CamiID == '' || km_form.value.CamiBalance == '') {
    ElMessage.error('请获取卡密ID 或者卡密余额')
    return false
  }

  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: `INSERT INTO cami (CamiID,CamiBalance,CamiCreateTime) VALUES ('${
        km_form.value.CamiID
      }','${km_form.value.CamiBalance}','${time(new Date().getTime())}')`,
      dbName: 'userglobal'
    } 
  }) 
  console.log(res)
  if (res.packageContent.packageStatus === 0) {
    ElMessage.success('添加成功')
    await get_list('SELECT * FROM cami ORDER BY cami.IndexID LIMIT 15 OFFSET 0', 'userglobal')
    dialogVisible.value = false
  }else{
    ElMessage.error('添加失败')
  }
}

const get_cm = async () => {
  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminCreateCard',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password
    }
  })
  console.log(res)
  if (res.packageContent.packageMsg) {
    km_form.value.CamiID = res.packageContent.packageMsg
    ElMessage.success('卡密ID获取成功')
  }
}

// 模糊查询
const search_inp = ref('')
const search_click = async () => {
  if (search_inp.value == '') {
    await get_list('SELECT * FROM cami ORDER BY cami.IndexID LIMIT 15 OFFSET 0', 'userglobal')
  } else
    await get_list(
      `SELECT * FROM cami WHERE IndexID LIKE '%${search_inp.value}%' OR Distributor LIKE  '%${search_inp.value}%' OR CamiID LIKE '%${search_inp.value}%' OR AgentUserName LIKE '%${search_inp.value}%' OR OwnerUserName LIKE '%${search_inp.value}%' OR CamiUseTime LIKE '%${search_inp.value}%'`,
      'userglobal'
    )
}

// 分配
const allot = (row) => {
  console.log(row)
}
// 双击
const daili_list = ref([])
const daili_model = ref('')
const db_click = async (row) => {
  // e.stopPropagation();
  // 代理列表
  daili_model.value = ''
  daili_list.value = await get_list_daili('SELECT * FROM agentuser', 'userglobal')
  console.log(daili_model.value)

  tableData.value.forEach((item) => {
    item['status'] = false
  })
  console.log(row)
  row['status'] = true
}

// 失去焦点
const daili_blur = async (row) => {
  console.log(row)
  console.log(daili_model.value)
  row['status'] = false
  if (daili_model.value == '') {
    return false
  }

  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: `UPDATE cami SET AgentUserName = '${daili_model.value}'  WHERE IndexID = '${row.IndexID}'`,
      dbName: 'userglobal'
    }
  })

  console.log(res)
  if (res && res.packageContent.packageStatus === 0) {
    ElMessage({
      message: '更新成功',
      type: 'success'
    })
    if ((page.value - 1) * pageSize.value - 1 <= 0) {
      await get_list(
        `SELECT * FROM cami ORDER BY cami.IndexID LIMIT ${pageSize.value} OFFSET 0`,
        'userglobal'
      )
    } else {
      await get_list(
        `SELECT * FROM cami ORDER BY cami.IndexID LIMIT ${pageSize.value} OFFSET ${
          (page.value - 1) * pageSize.value
        }`,
        'userglobal'
      )
    }
  } else {
    ElMessage({
      message: '更新失败',
      type: 'error'
    })
  }
}

// 收回
const recycle = async (row) => {
  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: `UPDATE cami SET AgentUserName = null  WHERE IndexID = '${row.IndexID}'`,
      dbName: 'userglobal'
    }
  })

  console.log(res)
  if (res && res.packageContent.packageStatus === 0) {
    ElMessage({
      message: '收回成功',
      type: 'success'
    })
    await get_list('SELECT * FROM cami ORDER BY cami.IndexID LIMIT 15 OFFSET 0', 'userglobal')
  } else {
    ElMessage({
      message: '收回失败',
      type: 'error'
    })
  }
}

const table_click = () => {
  console.log(111)
  // tableData.value.map(item=>item.status = false)
}


// 修改
const edit_dialogVisible  = ref(false)
const edit_from = ref({

})
const edit_row = async(row)=>{
  console.log(row);
  daili_list.value = await get_list_daili('SELECT * FROM agentuser', 'userglobal')
  edit_dialogVisible.value = true
  edit_from.value = row
}
const edit_enter = ()=>{
console.log(edit_from.value);

}

// 获取列表
const tableData = ref([])
const get_list = async (sql, dbName) => {
  console.log(userInfo.value)

  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: sql,
      dbName: dbName
    }
  })

  let result = []
  if (res.packageContent.packageStatus === 0 && res.packageContent.packageMsg !== '成功') {
    // let data = JSON.parse(res.packageContent.packageMsg) || [];
    // tableData.value = data;
    // console.log(tableData.value);
    result = JSON.parse(res.packageContent.packageMsg)
  } else {
    result = []
  }
  tableData.value = result
  console.log(tableData.value)

  return result
}
// 代理列表
const get_list_daili = async (sql, dbName) => {
  console.log(userInfo.value)

  const res = await http.corsApi('/', 'post', {
    packID: '123456',
    packageType: 'adminSql',
    packageContent: {
      AgentUserName: userInfo.value.username,
      AgentUserPassword: userInfo.value.password,
      sql: sql,
      dbName: dbName
    }
  })

  let result = []
  if (res.packageContent.packageStatus === 0 && res.packageContent.packageMsg !== '成功') {
    // let data = JSON.parse(res.packageContent.packageMsg) || [];
    // tableData.value = data;
    // console.log(tableData.value);
    result = JSON.parse(res.packageContent.packageMsg)
  } else {
    result = []
  }

  return result
}

const time = (t) => {
  var dt = new Date(t)
  var y = dt.getFullYear()
  var m = dt.getMonth() + 1
  var d = dt.getDate()
  var h = dt.getHours()
  var mi = dt.getMinutes()
  var s = dt.getSeconds()

  return `${y}-${m}-${d}-${h}-${mi}-${s}`
}
</script>
  
  <style scoped lang="scss">
.agent {
  height: 100%;
  .title-btn {
    padding-right: 50px;
  }
}
</style>